var mi = {}; //密友圈名字空间
(function(mi) {
	var utils = {
		getQuery: function(a) {
			var b = arguments[1] || window.location.search,
				c = new RegExp("(^|&)" + a + "=([^&]*)(&|$)"),
				d = b.substr(b.indexOf("?") + 1).match(c);
			return null != d ? d[2] : ""
		},
		namespace: function(str) {
			for (var arr = str.split(","), i = 0, len = arr.length; len > i; i++)
				for (var arrJ = arr[i].split("."), parent = {}, j = 0, jLen = arrJ.length; jLen > j; j++) {
					var name = arrJ[j],
						child = parent[name];
					0 === j ? eval("(typeof " + name + ')==="undefined"?(' + name + '={}):"";parent=' + name) : parent = parent[name] = "undefined" == typeof child ? {} : child
				}
		},
		urlReplace: function(a, b) {
			var c = b.url || location.search.substring(1),
				d = new RegExp("(^|&)(" + a + "=)([^&]*)"),
				e = b.content ? b.content : "";
			return c.replace(d, function(a, b, c) {
				return e ? b + c + e : ""
			})
		},
		isWeiXin: function() {
			var ua = window.navigator.userAgent.toLowerCase();
			return ua.match(/MicroMessenger/i) == 'micromessenger';
		},
		getCookie: function(a) {
			var b = new RegExp("(^| )" + a + "(?:=([^;]*))?(;|$)"),
				c = document.cookie.match(b);
			return c ? c[2] ? unescape(c[2]) : "" : null
		},
		delCookie: function(a, b, c, d) {
			var e = utils.getCookie(a);
			if (null != e) {
				var f = new Date;
				f.setMinutes(f.getMinutes() - 1e3), b = b || "/", document.cookie = a + "=;expires=" + f.toGMTString() + (b ? ";path=" + b : "") + (c ? ";domain=" + c : "") + (d ? ";secure" : "")
			}
		},
		setCookie: function(a, b, c, d, e, f) {
			var g = new Date,
				c = arguments[2] || null,
				d = arguments[3] || "/",
				e = arguments[4] || null,
				f = arguments[5] || !1;
			c ? g.setMinutes(g.getMinutes() + parseInt(c)) : "", document.cookie = a + "=" + escape(b) + (c ? ";expires=" + g.toGMTString() : "") + (d ? ";path=" + d : "") + (e ? ";domain=" + e : "") + (f ? ";secure" : "")
		}
	};
	/**
	 * [PRODUCT_ORDERDETAIL 订单详情]
	 * @type {Object}
	 */
	mi.PRODUCT_ORDERDETAIL = {
		init: function() {
			this.initPageBtn();
		},
		initPageBtn: function() {
			var a = [];
			switch (window.dealStatus) {
				case 1:
					a.push('<div class="mod_cell ui_p10"><div class="qb_flex">'), a.push($("#cancel-tpl").html()), a.push($("#topay-tpl").html()), a.push("</div></div>");
					break;
				case 2:
					2 == window.payType && (a.push('<div class="qb_flex qb_mb10 ui_gap">'), a.push($("#cancel-tpl").html()), a.push("</div>")), 1 == window.payType && a.push($("#drawback-tpl").html());
					break;
				case 3:
					2 == window.payType ? $("#suc-msg").removeClass("qb_none") : (a.push('<div class="qb_flex qb_mb10 ui_gap">'), a.push($("#recv-tpl").html()), a.push("</div>"));
					break;
				case 7:
					a.push($("#onback-tpl").html().replace(/{#text#}/, "退款中..."));
					break;
				case 8:
					a.push($("#onback-tpl").html().replace(/{#text#}/, "退款完成"));
					break;
				case 18:
					break;
				case 19:
					a.push($("#cancelgoods-tpl").html())
			}
			$("#operate_area").html(a.join(""))
		}
	};

	mi.PRODUCT_ADDRESS = {
		init: function() {
			this._initValidate();
		},
		_initValidate: function() {
			var me = this;
			var config = {};
			config = {
				"name": {
					rule: {
						required: {
							message: "请填写收件人姓名"
						}
					},
					pos: "bottom"
				},
				"mobile": {
					rule: {
						required: {
							message: "请填写联系电话"
						},
						mobile: {
							message: "请输入11位手机号码"
						}
					},
					pos: "bottom"
				},
				"address": {
					rule: {
						required: {
							message: "请填写详细地址"
						}
					},
					pos: "bottom"
				}
			}
			var va = new Validate("page_address_add", config);
			$("#save_addr").tap(function() {
				va.validate(function(result) {
					if (result) {
						me.save();
					}
				});
			});
		},
		save: function() {
			var fullName = $('#name').val();
			var phone = $('#mobile').val();
			var address = $('#address').val();
			var data = {
				"fullname": $.trim((fullName || "").replace(/s+/g,"")),
				"phone": $.trim((phone || "").replace(/s+/g,"")),
				"address": $.trim((address||"").replace(/s+/g,""))
			}
			var p = {
				'module': 'product',
				'method': 'updateUserInfo',
				'params': JSON.stringify(data)
			};
			$.ajax({
				url: window.basePath,
				dataType: "json",
				type: "POST",
				data: p,
				success: function(d) {
					var params = {
						"type": "buy",
						"sid": -1,
						"tplid": window.tplid,
						"id": window.preOid
					}

					if (window.rootId) {
						params["rootid"] = rootId;
					}
					url = '&module=product&method=getOrderDetail&force=1&params=';
					url = url + JSON.stringify(params);
					location.href = window.hrefPath + url;
				}
			});
		}
	};
	mi.PRODUCT_DETAIL = {
		propList: [],
		matchProperty: [],
		buyProperty: "",
		selectedCount: 0,
		init: function(id) {
			this.id = id;
			this._initParam();
			this._initClickEvent();
			this._addFavorite(id);
			this.getCartGoodsNum();
		},
		_initParam: function() {
			this.buyProperty = "";
			this.errorMsg = "";
			this._initStock(), (window.inventory == 0 || window.sku.length > 0) && this._initProperty();
			(window.inventory == 1 && window.totalInventoryCount == 0 && window.sku.length == 0) && ($("#add-cart").addClass("btn_disabled") && $("#buy-now").addClass("btn_disabled") && $("#buy-now").removeClass("btn_strong"));
		},
		_initStock: function() {
			var a = this;
			$.each(window.availSku, function(b) {
				a.propList.push(b)
			});
		},
		getCartGoodsNum:function () {
			var customerId=$.util.getParam("customerId");
		    $.req.get("call.json?module=product&customerId="+customerId+"&method=getCarNum",{
		        userName:buyParams.userName,
		        params:{
		            "type":"buy",
		            "sid":"-1"
		        }
		    },function(data){
		        if(!data.code){
		            $("#carNum").text(data.total || 0);
		            if(data && data.total > 0){
		            	$("#car").addClass("to-car");
		            }else {
		            	$("#car").removeClass("to-car");
		            }
		        } 
		    });
		},
		_initPropertyEvent: function(e) {
			var b = $(e.target);
			if (!b.hasClass("current") && !b.hasClass("disabled")) {
				b.addClass("current").siblings().removeClass("current");
				var c = b.parent();
				this.loopProp(b.attr("data-value"), c.attr("index"), c.attr("skuName"))
			}
		},
		_initProperty: function() {
			var a = this,
				b = window.sku,
				c = $("#prop-tpl").html(),
				d = '<span data-value="{#key#}" class="property {#className#}">{#optionName#}</span>',
				e = [],
				f = [],
				g = {};
			b.forEach(function(b, h) {
				var i = [];
				b.pList.forEach(function(a) {
					var c, e = a;
					c = d.replace(/{#key#}/, e).replace(/{#optionName#}/, a).replace(/{#className#}/, 1 === b.pList.length ? "current" : ""), i.push(c)
				}), 1 == b.pList.length ? (g.key || (g.key = b.pList[0], g.index = h,
						g.propName = b.pName), a.matchProperty[h] = b.pList[0],
					a.selectedCount++) : f.push(b.pName);

				e.push(c.replace(/{#index#}/, h).replace(/{#pName#}/g,
					b.pName).replace(/{#pList#}/, i.join("")).replace(/{#availSku#}/, b.availSku));

			});
			$('#buyNum').prop('disabled', true);
			a.errorMsg = "请选择" + f.join("/"), $("#prop-list").html(e.join("")),
				a.pNodeList = $(".mod_property"), g.key && a.loopProp(g.key, g.index, g.propName), g = null
		},
		_addFavorite: function() {
			var id = this.id;
			$("#favorite").tap(function() {
				var me = $(this);
				var favorite = $(this).attr("favorite");
				var customerId = $.util.getParam("customerId");
				if (favorite == "0") {
					var method = "addFavorite";
				} else {
					var method = "removeFavorite";
				}
				if($(this).hasClass("fav1")){
					return;
				}
				$("#FavMask").tap(function(){
					$(this).hide();
				});
				$.util.pageLoading.show();
				$.req.get("call.json?customerId=" + customerId + "&module=product&method=" + method, {
					params: {
						"id": id
					}
				}, function(data) {
					if (data && !data.code) {
						if (favorite == "0") {
							if(!$.util.cookie('isShowFav')){
								$("#FavMask").show();
								$.util.cookie('isShowFav',1,{path:"/"});
							}
							me.html("已收藏");
							me.attr("favorite", 1);
							me.addClass('fav1');
						} else {
							me.html("收藏");
							me.attr("favorite", 0);
						}
					}
					$.util.pageLoading.hide();
				});
			});
		},
		pageSize:10,
		page:0,
		_initEvent:function(){
			var me=this;
			$.util.initDataLoading({
				me:mi.PRODUCT_DETAIL,
				lastChildren:function(){
					return $("#p-comment .main:last");
				},
				page:function(){
					return mi.PRODUCT_DETAIL.page;
				},
				pageCount:function(){
					return mi.PRODUCT_DETAIL.pageCount;
				}
			});
		},
		_renderList:function(data,page,callback){
			var me=this;
			if(data){
				var html=template("Tpl", data),
					container = $("#p-comment");
				if(data.code){
					container.html(html);
				}else{
					container.append(html);
				}
				me.page=page;
				me.pageCount=data.pageCount;
				callback && callback();
			}
		},
		_loadList:function(page,callback){
			var me=this;
			var customerId = $.util.getParam("customerId");
			$.req.get("call.json?customerId=" + customerId + "&module=product&method=getcommentList",{
				params: {
					"id": me.id,
					"start":page,
					"limit":me.pageSize
				}
			},function(data){
				if(data){
					me._renderList(data,page,callback);
				}
			});
		},
		_initClickEvent: function() {
			var me = this;
			this._initSlide();
			if ((window.inventory == 0 || window.totalInventoryCount > 0 || window.sku.length > 0)) {
				$(".minus,.plus").on("tap", function(e) {
					me._initBuyNum(e);
				});
				$(".mod_property span").on("tap", function(e) {
					me._initPropertyEvent(e);
				});
				$("#buy-now").click(function() {
					me._initBuy();
				});
			}
		},
		loopProp: function(a, b, c) {
			var d = [],
				e = !0,
				f = this;
			f.matchProperty[b] || f.selectedCount++, f.matchProperty[b] = a, d[b] = a,
				$.each(window.sku, function(a, b) {
					var d, g, h = b.pName,
						i = b.pList,
						j = f.pNodeList.eq(a),
						k = j.find("span");
					h !== c && $.each(i, function(a, b) {

					})
				});
			f.statisticSelected();
		},
		statisticSelected: function() {
			var a, b, c = this;
			if (c.selectedCount == window.sku.length) {

				if ($('#buyNum').prop('disabled') == true) {
					$('#buyNum').prop('disabled', false);
				}
				$('#inventory_count').show();
				var d = c.matchProperty.join("|");
				c.buyProperty = d;
				a = window.availSku[d];
				if (a) {
					$("#buyNum").val(1);
					b = a.stockCount;
					$("#stock-num").html(b);
				}
				c.curStock = parseInt(b, 10);
				if (window.inventory == 1 && b == 0) {
					$("#add-cart").addClass("btn_disabled");
					$("#buy-now").addClass("btn_disabled");
					$("#buy-now").removeClass("btn_strong");

				}
				if (window.inventory == 1 && b > 0) {
					$("#add-cart").removeClass("btn_disabled");
					$("#buy-now").removeClass("btn_disabled");
					$("#buy-now").addClass("btn_strong")
				}
			}
		},
		_initBuyNum: function(e) {
			var buyNum = $("#buyNum"),
				target = $(e.target),
				type = target.attr("tag"),
				num = 1 * buyNum.val();
			if (target.hasClass("disabled")) {
				return;
			}
			if (num) {
				if (isNaN(num)) {
					buyNum.val(1);
				} else {
					var ktotal = buyNum.data('ktotal');
					var total = buyNum.data('total');
					if ($("#prop-list dl").length != 0) {
						var size = $("#prop-list dl").eq(0).find("span.current").data("value");
						var color = $("#prop-list dl").eq(1).find("span.current").data("value");
						var availSku = $("#prop-list dl").eq(0).data('value');
						var tmp = decodeURIComponent(availSku);
						var kc = JSON.parse(eval("'" + tmp + "'"));
						if ($("#prop-list dl").eq(0).length != 0 && size == null) {
							return $.util.alert('没有选择规格');
						}
						if ($("#prop-list dl").eq(1).length != 0 && color == null) {
							return $.util.alert('没有选择规格');
						}
						ktotal = buyNum.data('nowKc');
					}
					if (type == "add") {
						if (num < 999 || (total != null && ktotal && num < parseInt(ktotal))) {
							buyNum.val(++num);
							$("#sub").removeClass("disabled");
							if (num > 999 || (total != null && ktotal && num > (parseInt(ktotal)) - 1)) {
								$("#plus").addClass("disabled");
							}
						}
					} else {
						if (num > 1) {
							buyNum.val(--num);
							$("#plus").removeClass("disabled");
							if (num < 2) {
								$("#sub").addClass("disabled");
							}
						}
					}
				}
			}
		},
		_initBuy: function() {
			var customerId = $.util.getParam("customerId");
			if (!$("#buy-now").hasClass("btn-disabled")) {
				if (window.sku.length > 0 && !this.buyProperty)
					return $.util.alert(this.errorMsg);
				var sizes = '';
				var colors = '';
				var customerId = $.util.getParam("customerId");
				prop = this.buyProperty;
				var params = window.buyParams;
				if (prop != null) {
					if (window.color != null && window.size != null) {
						var propItems = prop.split("|");
						sizes = encodeURIComponent(propItems[0]);
						colors = encodeURIComponent(propItems[1]);
					} else if (window.size != null) {
						sizes = encodeURIComponent(prop);
					} else if (window.color != null) {
						colors = encodeURIComponent(prop);
					}
					if (sizes) {
						params.sizes = sizes;
						params.colors = colors;
					}
				}
				if ($("#stock-num") && $("#stock-num").html() == 0) {
					$.util.alert("库存不足");
					return;
				}
				$.util.pageLoading.show();
				$(this).addClass("btn-disabled");
				$.req.get("call.json?customerId=" + customerId + "&module=product&method=preSubmitOrder", {
					params: $.extend(params, {
						"sizes": sizes,
						"colors": colors,
						"counts": $("#buyNum").val()
					})
				}, function(data) {
					if (data.hasOwnProperty('code')) {
						$("#buy-now").removeClass("btn_disabled");
						$.util.alert(data.msg);
					} else {
						var p = {
							"tplid": 1,
							"id": data.id
						}
						location.href = window.hrefPath + '&module=product&method=getOrderDetail&force=1&params=' + encodeURIComponent(JSON.stringify(p));
					}
					$.util.pageLoading.hide();
				});
			}
		},
		_initSlide: function() {
			var loop=$("#detail-slider li").size() > 2;
			$("#detail-slider").slider({
				loop: loop,
				imgZoom: true,
				arrow: false,
				autoPlay: false,
				slide: function(e, to, from) {

				}
			});
			$(".ui-slider-dots").css("marginLeft", $(".ui-slider-dots").width() / 2 * -1);
		}
	};
	mi.PRODUCT_ORDERPAY = {
		init: function() {
			this._initEvent();
		},
		/**
		 * [_initEvent 初始化页面按钮点击事件]
		 * @return {[type]}
		 */
		_initEvent: function() {
			var me = this;
			$("#toAddrList,#mdAddrBtn").tap(function() {
				me.initAddr();
			});
			$("#submitOrder").tap(function() {
				me.submitOrder();
			});
		},
		/**
		 * [submitOrder 提交订单一键支付]
		 * @return {[type]}
		 */
		submitOrder: function() {
			var btn = $("#submitOrder");
			var me = this;
			var params = {
				"id": window.orderId,
				"remark": $("#remark").val(),
				"sid": -1,
				"type": window.buyType,
				"fullName": (window.fullName || "").replace(/\s+/g,""),
				"address": (window.address || "").replace(/\s+/g,""),
				"phone": (window.phone || "").replace(/\s+/g,""),
				"paytype": "tenpay",
				"dtype": "delivery"
			}
			if (!btn.hasClass("btn_disabled")) {
				//判断收货地址是否为空
				if (window.fullName == '' || window.phone == '' || window.address == '') {
					return $.util.alert("请填写收货信息");
				}
				btn.addClass("btn_disabled");
				$.ajax({
					url: window.basePath,
					dataType: "json",
					type: "POST",
					data: {
						module: 'product',
						method: 'submitOrder',
						params: JSON.stringify(params)
					},
					success: function(data) {
						if (typeof(data.code) !== "undefined") {
							btn.removeClass("btn_disabled");
							$.util.alert(data.msg);
							return;
						}
                       
                        location.href = data.url;
					},
					error:function(){
						btn.removeClass("btn_disabled");
						$.util.alert("购买失败");
					}
				})
			}
		},
		cancelOrder: function(callback) {
			var btn = $("#submitOrder");
			$.ajax({
				url: window.basePath,
				dataType: "json",
				type: "POST",
				data: {
					module: 'product',
					method: 'cancelWxOrder',
					params: '{"oid":' + window.orderId + '}'
				},
				success: function() {
					btn.removeClass("btn_disabled");
					callback && callback();
				}
			});
		},
		/**
		 * [initAddr 初始化地址选择]
		 * @return {[type]}
		 */
		initAddr: function() {
			var payType = "wxpay";
			var params = {
				"tplid": 1,
				"orderId": orderId,
				"payType": payType
			};
			if (window.rootId) {
				params.rootId = rootId;
			}
			var editAddrUrl = window.hrefPath + '&module=product&method=getAddr&params=' + JSON.stringify(params);
			if (utils.isWeiXin()) {
				$.ajax({
					url: window.basePath,
					dataType: "json",
					type: "POST",
					timeout: 15000,
					data: {
						'module': 'product',
						'method': 'getAddrSign',
						'params': JSON.stringify({
							"url": encodeURIComponent(document.location.href)
						})
					},
					success: function(data) {
						if (data && !data.code) {
							try {
								WeixinJSBridge.invoke('editAddress', {
									"appId": data.appId,
									"scope": data.scope,
									"signType": data.signType,
									"addrSign": data.addrSign,
									"timeStamp": data.timeStamp,
									"nonceStr": data.nonceStr
								}, function(res) {
									if (res.err_msg != 'edit_address:ok') {
										if (res.err_msg == 'edit_address:fail') {
											return;
										} else {
											//微信中编辑地址失败则使用
											var param = window.id == '' ? '' : ',"oid":' + window.id;
											location.href = editAddrUrl;
										}
									}

									window.fullName = res.userName || "";
									window.phone = res.telNumber || "";
									var addr = res.addressCitySecondStageName + res.proviceFirstStageName + res.addressDetailInfo;
									window.address = addr || "";
									var bp = {
										'module': 'product',
										'method' : 'updateUserInfo',
										'params' : '{"fullname":"' + window.fullName.replace(/\s+/g,"") +
										'","phone":"' + window.phone.replace(/\s+/g,"") +
										'","address":"' + window.address.replace(/\s+/g,"") + '"}'
									};
									$.ajax({
										url:'call.json?customerId=' + hrefParamsArray["customerId"],
										dataType: "json",
										type: "POST",
										data: bp,
										success: function (br) {
										}
									});
									$("#addr_fullName").html(res.userName);
									$("#addr_phone").html(res.telNumber);
									$("#addr_detail").html(addr);
									$("#addRbox").show();
									$("#toAddrList").hide();
								});
							} catch (e) {
								$.util.alert("操作失败，请确保在微信浏览器中操作");
								return false;
							}
						} else {
							location.href = editAddrUrl;
						}
					}
				});
			} else {
				location.href = editAddrUrl;
			}
		}
	}
})(mi);